package gripper.ftp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ConcurrentSkipListSet;

import gripper.ftp.info.ServerInfo;
import gripper.ftp.prop.PropManager;
import gripper.ftp.prop.User;

public class FtpServer implements Runnable {
	Thread thread = new Thread(this);
	public PropManager propManager;
	ServerInfo serverInfo;
	ConcurrentSkipListSet<FtpSession> sessions;
	private boolean run=true;
	public void start() {
		sessions=new ConcurrentSkipListSet<>();
		prepare();
		thread.start();
		serverInfo=new ServerInfo(this,sessions);
	}
	public void start(String user,String password,String path){
		sessions=new ConcurrentSkipListSet<>();
		prepare(user,password,path);
		thread.start();
		serverInfo=new ServerInfo(this,sessions);
	}
	public void start(User ...users){
		sessions=new ConcurrentSkipListSet<>();
		prepare(users);
		thread.start();
		serverInfo=new ServerInfo(this,sessions);
	}
	
	public void close(){
		run=false;
	}
	public void run() {
		try (ServerSocket ss = new ServerSocket();){
			ss.bind(new InetSocketAddress(21));
			while (run) {
				Socket sk = ss.accept();
				FtpSession ftpSession = new FtpSession(this, sk,serverInfo);
				sessions.add(ftpSession);
				ftpSession.work();
			}
		} catch (IOException e) {
		}
	}

	private void prepare() {
		try {
			propManager = new PropManager();
		} catch (FileNotFoundException e) {
			Path path = Paths.get("ftp.properties");
			try {
				Files.createFile(path);
				propManager = new PropManager();
			} catch (IOException e1) {
			}
		} catch (IOException e) {
		}
	}
	private void prepare(String user,String password,String path){
		if(path==null){
			path=System.getProperty("user.dir");
		}
		if(!path.endsWith(File.separator)){
			path+=File.separator;
		}
		propManager = new PropManager(user,password,path);
	}
	private void prepare(User[] users) {
		propManager = new PropManager(users);
	}
	public void remove(FtpSession ftpSession) {
		sessions.remove(ftpSession);
	}
	public ServerInfo getServerInfo(){
		return serverInfo;
	}
}
